package com.ja.openchat.viewmodels;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.UserInfo;
import com.ja.openchat.ui.me.SetPayPwdFragment;
import com.sahooz.library.Country;
import com.sahooz.library.CountryPickFragment;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;

import static com.blankj.utilcode.util.StringUtils.getString;


public class SetPayPwdByPhoneCodeViewModel extends BaseViewModel {
    //手机号的绑定
    public ObservableField<String> userPhone = new ObservableField<>("");
    public ObservableField<String> userCode = new ObservableField<>("");
    //国家和区号的绑定
    public ObservableField<Country> country = new ObservableField<>(new Country(86, App.getInstanse().getString(R.string.china_text), "CN", 0));
    //用户名清除按钮的显示隐藏绑定
    public ObservableInt clearBtnVisibility = new ObservableInt();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public static final String TOKEN_LOGINBYPHONEVIEWMODEL_FINISH = "token_setpaypwdbyphonecodeviewmodel_finish";

    public class UIChangeObservable {
        //倒计时观察者
        public SingleLiveEvent<String> timerEvent = new SingleLiveEvent<>();
    }

    public SetPayPwdByPhoneCodeViewModel(@NonNull Application application) {
        super(application);
        uc.timerEvent.setValue("验证码");
        Messenger.getDefault().register(this, SetPayPwdByPhoneCodeViewModel.TOKEN_LOGINBYPHONEVIEWMODEL_FINISH, () -> finish());
    }

    public void setCountry(String country) {
        this.country.set(Country.fromJson(country));
    }


    //清除用户名的点击事件, 逻辑从View层转换到ViewModel层
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            userPhone.set("");
        }
    });
    //用户名长度改变的回调事件
    public BindingCommand onTextChangeCommand = new BindingCommand<>(new BindingConsumer<String>() {
        @Override
        public void call(String s) {
            KLog.d("onTextChangeCommand==" + s);
            if (TextUtils.isEmpty(s)) {
                clearBtnVisibility.set(View.INVISIBLE);
            } else {
                clearBtnVisibility.set(View.VISIBLE);
            }
        }
    });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand = new BindingCommand<>(new BindingConsumer<Boolean>() {
        @Override
        public void call(Boolean hasFocus) {
            if (hasFocus && !TextUtils.isEmpty(userPhone.get())) {
                clearBtnVisibility.set(View.VISIBLE);
            } else {
                clearBtnVisibility.set(View.INVISIBLE);
            }
        }
    });
    //选择国家按钮的点击事件
    public BindingCommand countryOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivityForResult(CountryPickFragment.class.getCanonicalName(), 1);
        }
    });
    //点击验证码
    public BindingCommand phoneCodeClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //国家码
            if (StringUtils.isEmpty(country.get().codeStr)) {
                showWarnTip(getString(R.string.country_code_null_hint));
                return;
            }
            //手机号码
            if (StringUtils.isEmpty(userPhone.get())) {
                showWarnTip(getString(R.string.phone_null_hint));
                return;
            }
            addSubscribe(Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(aLong -> {
                        int time = (int) (59 - aLong);
                        KLog.d("aLong==" + time);
                        if (time > 0) {
                            uc.timerEvent.setValue(time + "秒");
                        } else {
                            uc.timerEvent.setValue("验证码");
                        }
                    })
                    .doOnComplete(() -> {
                        //倒计时完毕事件处理
                        KLog.d("doOnComplete==");
                        uc.timerEvent.setValue("验证码");
                    })
                    .subscribe());
            getPhoneCode();
        }
    });
    //下一步按钮的点击事件
    public BindingCommand nextOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SetPayPwdFragment.class.getCanonicalName());
            finish();
//            check();
        }
    });

    private void check() {
        check(userCode.get());
    }

    private void getPhoneCode() {
        UserInfo.getUserInfo().isPasswordLoginType = false;
        UserInfo.getUserInfo().isPasswordRegisterType = false;
        showProgress();
        TelegramManager.getTelegramManager().setAuthenticationPhoneNumber(getApplication(), String.format("+%s %s", country.get().code, userPhone.get()), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    //{"@type":"error","code":400,"message":"PASSWORD_VERIFY_INVALID","@extra":4}
                    //USER_PASSWORD_NEEDED 必须输入密码
//                        USERNAME_NOT_EXIST 用户名不存在
//                        USER_PASSWORD_NOT_SET 用户未设置密码
//                        PASSWORD_VERIFY_INVALID 密码校验错误
//                        IP_ADDRESS_BANNED 登录ip被禁用
//                        USER_BINDED_IP_ADDRESS 登录用户已经绑定ip
                    if (obj.errCode == 400) {
                        if ("400_IP_ADDRESS_BANNED".equals(obj.errString)) {
                            showErrorTip("登录ip被禁用");
                            return;
                        }
                        if ("400_USER_BINDED_IP_ADDRESS".equals(obj.errString)) {
                            showErrorTip("登录用户已经绑定ip");
                            return;
                        }
                    }
                    showErrorTip(getString(R.string.invalid_phone));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        if (flagStop) return;
        switch (tg_event.event) {
            case EUser_Td_Input_Code:
                //发送验证码成功
                KLog.d("EUser_Td_Input_Code success");
                break;
            default:
                break;
        }
    }

    private void check(String smsCode) {
        //国家码
        if (StringUtils.isEmpty(country.get().codeStr)) {
            showWarnTip(getString(R.string.country_code_null_hint));
            return;
        }
        //手机号码
        if (StringUtils.isEmpty(userPhone.get())) {
            showWarnTip(getString(R.string.phone_null_hint));
            return;
        }
        if (StringUtils.isEmpty(userCode.get())) {
            showWarnTip(getString(R.string.verification_code_null_hint));
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().checkAuthenticationCode(getApplication(), smsCode, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    if (obj.errCode == 420) {//验证码错误次数过多，请5分钟后重新登录
                        showErrorTip(getString(R.string.invalid_sms_code_is_block));
                        finish();
                    } else {
                        showErrorTip(getString(R.string.invalid_sms_code));
                    }
                }else {
                    startContainerActivity(SetPayPwdFragment.class.getCanonicalName());
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

}
